<template>
  <div class="app-container">
    用户设置
    <el-form label-width="120px">
      <el-row :gutter="10">
        <el-col :xs="24" :sm="16" :md="12">
          <el-form-item label="分类名">
            <el-select v-model="contentObj.mid" placeholder="请选择分类">
              <el-option
                v-for="item in metas"
                :key="item.mid"
                :label="item.name"
                :value="item.mid"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :xs="24" :sm="16" :md="12">
          <el-form-item label="状态">
            <el-select v-model="contentObj.status" placeholder="请选择状态">
              <el-option
                v-for="item in selectStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :xs="24" :sm="16" :md="12">
          <el-form-item label="方式">
            <el-select v-model="contentObj.ctype" placeholder="请选择方式">
              <el-option
                v-for="item in selectCtype"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :xs="24" :sm="14" :md="12">
          <el-form-item label="用户id">
            <el-input type="number" v-model="contentObj.uid" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :xs="24" :sm="14" :md="12">
          <el-form-item label="发表内容">
            <el-input
              autosize
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 10 }"
              v-model="textConent"
            />
            <el-button type="primary" @click="faceContent" circle>😀</el-button>
            <div class="browBox" v-if="faceShow">
              <ul>
                <li
                  v-for="(item, index) in faceList"
                  :key="index"
                  @click="getBrow(index)"
                >
                  {{ item }}
                </li>
              </ul>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :xs="24" :sm="14" :md="12">
          <div v-if="contentObj.ctype != 0">
            <el-form-item label="">
              <el-upload
                class="upload-demo"
                drag
                ref="upload"
                :action="fileUrl"
                multiple
                :limit="3"
                :on-change="uploadChange"
                list-type="picture"
                :auto-upload="false"
                :data="contentObj"
                :headers="headersObj"
                :with-credentials="true"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :on-exceed="handleExceed"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击选择图片</em>
                </div>
                <div class="el-upload__tip" slot="tip"></div>
              </el-upload>
            </el-form-item>
          </div>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" @click="save">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style lang="scss" scoped>
.browBox {
  width: 300px;
  height: 220px;
  background: #e6e6e6;
  // position: absolute;
  bottom: 0;
  overflow: scroll;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    li {
      width: 14%;
      font-size: 26px;
      list-style: none;
      text-align: center;
    }
  }
}
</style>

<script>
//引入接口定义的js文件
import contentSet from "@/api/contentSet";
import metaSet from "@/api/metaSet";
import { getToken } from "@/utils/auth";
const appData = require("@/assets/emojis.json");

export default {
  data() {
    return {
      textConent: "",
      faceShow: false,
      faceList: [],
      contentObj: { ctype: "0" },
      headersObj: {},
      getBrowString: "",
      metas: [], //分类集合
      fileUrl: process.env.VUE_APP_BASE_API + "/admin/content/fileUpload",
      selectStatus: [
        {
          value: "0",
          label: "审核",
        },
        {
          value: "1",
          label: "正常",
        },
        {
          value: "2",
          label: "下架",
        },
      ],
      selectCtype: [
        {
          value: "0",
          label: "文字",
        },
        {
          value: "1",
          label: "图片",
        },
        {
          value: "2",
          label: "视频",
        },
      ],
    };
  },
  //页面渲染之前执行
  created() {
    this.getMetaAll();
  },
  mounted: function () {
    this.$nextTick(function () {
      //元素加载完成后执行的代码
      this.headersObj["token"] = getToken();
    });
    for (let i in appData) {
      this.faceList.push(appData[i].char);
    }
  },
  methods: {
    faceContent() {
      this.faceShow = !this.faceShow;
    },
    // 获取用户点击之后的标签 ，存放到输入框内
    getBrow(index) {
      const emoji = this.faceList[index];
      this.textConent += emoji;
    },
    //文件数量超过限制
    handleExceed(files, fileList) {
      this.$message({
        type: "error",
        message: "添加失败，数量超出限制!",
      });
    },
    //上传文件成功
    uploadSuccess(response, file, fileList) {},
    //上传文件失败
    uploadError(err, file, fileList) {
      console.log(err);
      this.$message({
        type: "error",
        message: "上传失败," + err.data,
      });
    },
    //上传文件判断
    uploadChange(file, fileList) {
      // 拿到当前上传图片的name，判断其后缀名是否符合

      let type = this.isImage(file.name);
      let type2 = this.isVideo(file.name);
      console.log("1" + type);
      console.log("2" + type2);

      this.fileList = fileList;
      let fileLength = this.fileList.length;

      //如果选择图片
      if (this.contentObj.ctype === 1) {
        if (!type) {
          // 若不符合图片类型，则让当前上传的文件去除掉即可，即从上传对列删除本次上传
          this.fileList.splice(fileLength - 1, 1);
          this.$message.error("只允许上传图片");
        }

        //如果是图片
        if (type) {
          const isLtxM = file.size / 1024 / 1024 < 5;
          if (!isLtxM) {
            this.fileList.splice(fileLength - 1, 1);
            this.$message.error("上传的图片大小不能超过 5MB!");
            return;
          }
        }
      }

      //如果选择视频
      if (this.contentObj.ctype === 2) {
        if (!type2) {
          // 若不符合图片类型，则让当前上传的文件去除掉即可，即从上传对列删除本次上传
          this.fileList.splice(fileLength - 1, 1);
          this.$message.error("只允许上传视频");
        }

        //如果是视频
        if (type2) {
          const isLtxM = file.size / 1024 / 1024 < 20;
          if (!isLtxM) {
            this.fileList.splice(fileLength - 1, 1);
            this.$message.error("上传的视频大小不能超过 20MB!");
          }
        }
        if (fileLength > 1) {
          this.fileList.splice(fileLength - 1, 1);
          this.$message.error("只允许上传1个视频");
        }
      }
      //修改数量
      this.contentObj.pictureNum = this.fileList.length;
    },
    isImage(fileName) {
      if (typeof fileName !== "string") return;
      let name = fileName.toLowerCase();
      return (
        name.endsWith(".png") ||
        name.endsWith(".jpeg") ||
        name.endsWith(".jpg") ||
        name.endsWith(".png")
      );
    },
    isVideo(fileName) {
      if (typeof fileName !== "string") return;
      let name = fileName.toLowerCase();
      return (
        //下面是视频格式的
        name.endsWith(".bmp") ||
        name.endsWith(".mp4") ||
        name.endsWith(".mov") ||
        name.endsWith(".avi")
      );
    },

    //分类列表
    getMetaAll() {
      metaSet.getAll().then((response) => {
        this.metas = response.data;
      });
    },
    //添加
    save() {
      this.contentObj.content = this.textConent;
      contentSet.add(this.contentObj).then((response) => {
        //提示
        this.$message({
          type: "success",
          message: "添加成功!",
        });
        this.contentObj.cid = response.data;
        //图文
        if (this.contentObj.ctype === 1 || this.contentObj.ctype === 2) {
          //上传文件
          this.$refs.upload.submit();
        }

        //跳转列表页面，使用路由跳转方式实现
       this.$router.push({ path: "/contentSet/list" });

      });
      // .catch((response) => {
      //   //添加错误
      //   this.$message({
      //     type: "error",
      //     message: response.message,
      //   });
      // });
    },
  },
};
</script>
